from urllib.parse import urlencode
from urllib import request
from selenium import webdriver
from selenium.webdriver import ChromeOptions
import time
from selenium.webdriver.common.by import By
import pickle

#可防止selenium被检测到合并了
#----------------------------------------------------
option = ChromeOptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
# option.add_argument('--headless')
# option.add_argument('--disable-gpu')

#如何让selenium规避掉可检测到的风险
bro = webdriver.Chrome(options=option)
bro.get('https://mail.qq.com')

def firstLogin():
    # iframe1 = bro.find_element(
    #     By.CLASS_NAME, "QQMailSdkTool_login_loginBox_qq_iframe")
    # bro.switch_to.frame(iframe1)
    # iframe2 = bro.find_element(By.NAME, 'ptlogin_iframe')
    # bro.switch_to.frame(iframe2)
    # trans = bro.find_element(By.XPATH, '//*[@id="switcher_plogin"]').click()
    # # 输入QQ号和密码并点击登录
    # user_name = bro.find_element(by='id', value='u')
    # user_name.send_keys('573561243')
    # user_password = bro.find_element(by='id', value='p')
    # user_password.send_keys('Ldx12138')
    # login_go_btn = bro.find_element(by='id', value='login_button')
    # login_go_btn.click()

    # windows = bro.window_handles
    # 切换到当前最新打开的窗口中
    # bro.switch_to.window(windows[-1])
    # time.sleep(30)
    time.sleep(15)
    # 保存cookies到文件
    with open('cookies.pkl', 'wb') as file:
        pickle.dump(bro.get_cookies(), file)

try:
    # 加载保存的cookies
  with open('cookies.pkl', 'rb') as file:
      cookies = pickle.load(file)
      for cookie in cookies:
          bro.add_cookie(cookie)
  # 刷新页面以应用cookies
  bro.refresh()
  time.sleep(3)
  bro.find_element(By.XPATH, '//*[@id="folder_1"]').click()
  print("登录成功！")
except Exception as e:
    firstLogin()
    print("登录状态未保持，出现错误：", e)

time.sleep(3)
iframe3 = bro.find_element(By.NAME,'mainFrame')
bro.switch_to.frame(iframe3)

table_list = bro.find_elements(By.XPATH,
                               '//*[@id = "div_showtoday"]/table')

url = "https://mamatata.fun/magic/api/pyApi/py_email"
for li in table_list:
    title_li = li.find_element(
      By.XPATH, ".//tbody/tr/td[3]/table/tbody/tr/td[1]/nobr")
    centent_li = li.find_element(
        By.XPATH, ".//tbody/tr/td[3]/table/tbody/tr/td[3]/div[1]/u")
    mailid_li = li.find_element(
        By.XPATH, ".//tbody/tr/td[1]/input").get_attribute('value')
    data = {'id': mailid_li, 'title_name': title_li.text,
            'content': centent_li.text}
    data = urlencode(data).encode('utf-8')
    try:
        req = request.Request(url, data=data, method='POST')
        response = request.urlopen(req)
        data = response.read().decode('utf-8')
        print(data)
    except Exception as e:
        print(f"出现错误: {e}")

time.sleep(10000)
bro.quit()
